package xyz.suancaiyu.userservice.web;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import xyz.suancaiyu.annotation.SysLogger;
import xyz.suancaiyu.dto.RespDTO;
import xyz.suancaiyu.userservice.entity.User;
import xyz.suancaiyu.userservice.service.UserService;
import xyz.suancaiyu.userservice.util.BPwdEncoderUtils;

/**
 * @author puruidong
 * @version 2019/1/24 22:34
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation(value = "注册", notes = "username和password为必选项")
    @PostMapping("/registry")
    @SysLogger("registry")
    public User createUser(@RequestBody User user) {
        //参数判读省略,TODO 需要增加判断用户是否已经存在.
        String entryPassword = BPwdEncoderUtils.BCryptPassword(user.getPassword());
        user.setPassword(entryPassword);
        return userService.createUser(user);
    }

    @ApiOperation(value = "登录", notes = "username和password为必选项")
    @PostMapping("/login")
    @SysLogger("login")
    public RespDTO login(@RequestParam String username, @RequestParam String password) {
        return userService.login(username, password);
    }

    @ApiOperation(value = "根据用户名获取用户", notes = "根据用户名获取用户")
    @PostMapping("/{username}")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    @SysLogger("getUserInfo")
    public RespDTO getUserInfo(@PathVariable("username") String username) {
        if(StringUtils.isNotBlank(username)){
            User user = userService.getUserInfo(username);
            return RespDTO.onSuc(user);
        }
        return null;
    }

//    @Autowired
//    private AmqpTemplate rabbitTemplate;
//    @GetMapping("/test")
//    public void test(){
//        rabbitTemplate.convertAndSend(RabbitConfig.queueName, "Hello from RabbitMQ!");
//    }


}
